package com.weiyi.mashangzhu.Landlord.Activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import com.lljjcoder.citypickerview.widget.CityPicker;
import com.squareup.okhttp.Request;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.Application.MyApp;
import com.weiyi.mashangzhu.Base.BaseActivity;
import com.weiyi.mashangzhu.R;
import com.weiyi.mashangzhu.Utils.LoadingDialog;
import com.weiyi.mashangzhu.Utils.SPUtils;
import com.weiyi.mashangzhu.Utils.T;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AdressActivity extends BaseActivity {

    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.et_dong)
    EditText etDong;
    @BindView(R.id.et_ceng)
    EditText etCeng;
    @BindView(R.id.et_room)
    EditText etRoom;
    String info,id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_adress);
        ButterKnife.bind(this);
        Intent intent=getIntent();
        info=intent.getStringExtra("info");
        id=intent.getStringExtra("id");
        if (info.equals("post")){
            //上传房源--地理位置
            if (MyApp.address_province!=null&&MyApp.address_city!=null&&MyApp.address_district!=null){
                tvCity.setText(MyApp.address_province.trim() + "-" + MyApp.address_city.trim() + "-" + MyApp.address_district.trim());
            }
            if (MyApp.address_address!=null){
                etAddress.setText(MyApp.address_address);
            }
            if (MyApp.address_loudong!=null){
                etDong.setText(MyApp.address_loudong);
            }
            if (MyApp.address_louceng!=null){
                etCeng.setText(MyApp.address_louceng);
            }
            if (MyApp.address_roomnum!=null){
                etRoom.setText(MyApp.address_roomnum);
            }
        }else {
            //修改房源--地理位置
            LoadingDialog.show(this);
            OkHttpUtils.get()
                    .addParams("token", SPUtils.get(this,"token","")+"")
                    .addParams("id",id)
                    .url(API.BaseApi_L+API.GetAddress)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Request request, Exception e) {
                            LoadingDialog.dismiss(AdressActivity.this);
                            T.showShort(AdressActivity.this,"数据获取失败，请稍后再试");
                        }

                        @Override
                        public void onResponse(String response) {
                            LoadingDialog.dismiss(AdressActivity.this);
                            try {
                                JSONObject jsonObject=new JSONObject(response);
                                if (jsonObject.getInt("status")==0){
                                    JSONArray jsonArray=jsonObject.getJSONArray("data");
                                    if (jsonArray!=null){
                                        JSONObject jsonObject1=jsonArray.getJSONObject(0);
                                        tvCity.setText(jsonObject1.getString("hProvince") + "-" + jsonObject1.getString("hCity") + "-" + jsonObject1.getString("hDistrict"));
                                        etAddress.setText(jsonObject1.getString("hAddress"));
                                        etDong.setText(jsonObject1.getString("hBuilding"));
                                        etCeng.setText(jsonObject1.getString("hFloor"));
                                        etRoom.setText(jsonObject1.getString("hRoomnum"));

                                    }

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    });

        }


    }

    private void selectAddress() {
        CityPicker cityPicker = new CityPicker.Builder(AdressActivity.this)
                .textSize(14)
                .title("地址选择")
                .titleBackgroundColor("#50FFFFFF")
//                .titleTextColor("#696969")
                .confirTextColor("#01A9F3")
                .cancelTextColor("#696969")
                .province("北京市")
                .city("北京市")
                .district("朝阳区")
                .textColor(Color.parseColor("#000000"))
                .provinceCyclic(true)
                .cityCyclic(false)
                .districtCyclic(false)
                .visibleItemsCount(5)
                .itemPadding(20)
                .onlyShowProvinceAndCity(false)
                .build();
        cityPicker.show();
        //监听方法，获取选择结果
        cityPicker.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
            @Override
            public void onSelected(String... citySelected) {
                //省份
                String province = citySelected[0];
                //城市
                String city = citySelected[1];
                //区县（如果设定了两级联动，那么该项返回空）
                String district = citySelected[2];
                //邮编
                String code = citySelected[3];
                //为TextView赋值
                MyApp.address_province = province.trim();
                MyApp.address_city = city.trim();
                MyApp.address_district = district.trim();
                tvCity.setText(province.trim() + "-" + city.trim() + "-" + district.trim());
            }
        });
    }

    @OnClick({R.id.back, R.id.city, R.id.baocun})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.city:
                //判断输入法的隐藏状态
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(view.getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    selectAddress();//调用CityPicker选取区域
                }
                break;
            case R.id.baocun:
                if (info.equals("post")){
                    Intent intent = new Intent();
                    if (MyApp.address_province != null && MyApp.address_city != null && MyApp.address_district != null && !(etAddress.getText()+"").equals("")&& !(etDong.getText()+"").equals("")&& !(etCeng.getText()+"").equals("")&& !(etRoom.getText()+"").equals("")) {
                       if (etDong.length()!=3||etCeng.length()!=3||etRoom.length()!=3){
                           T.showShort(AdressActivity.this,"楼栋号、楼层号或房间号格式不正确");
                       }else {
                           MyApp.address_address=etAddress.getText()+"";
                           MyApp.address_loudong=etDong.getText()+"";
                           MyApp.address_louceng=etCeng.getText()+"";
                           MyApp.address_roomnum=etRoom.getText()+"";
                           intent.putExtra("info", "完成");
                           setResult(0x0010, intent);
                           finish();

                       }
                    } else {
                        T.showShort(this,"请完善地理位置");
                    }
                }else {

                    String [] address=(tvCity.getText()+"").trim().split("-");
                    if (!(tvCity.getText()+"").equals("")&& !(etAddress.getText()+"").equals("")&& !(etDong.getText()+"").equals("") && !(etCeng.getText()+"").equals("")&& !(etRoom.getText()+"").equals("")) {
                        LoadingDialog.show(this);
                        OkHttpUtils.get()
                                .addParams("token",SPUtils.get(AdressActivity.this,"token","")+"")
                                .addParams("id",id)
                                .addParams("hProvince",address[0])
                                .addParams("hCity",address[1])
                                .addParams("hDistrict",address[2])
                                .addParams("hAddress",etAddress.getText()+"")
                                .addParams("hBuilding",etDong.getText()+"")
                                .addParams("hFloor",etCeng.getText()+"")
                                .addParams("hRoomnum",etRoom.getText()+"")
                                .url(API.BaseApi_L+API.UpdateAddress)
                                .build()
                                .execute(new StringCallback() {
                                    @Override
                                    public void onError(Request request, Exception e) {
                                        LoadingDialog.dismiss(AdressActivity.this);
                                        T.showShort(AdressActivity.this,"数据获取失败，请稍后再试");

                                    }

                                    @Override
                                    public void onResponse(String response) {
                                        LoadingDialog.dismiss(AdressActivity.this);
                                        try {
                                            JSONObject jsonObject=new JSONObject(response);
                                            if (jsonObject.getInt("status")==0){
                                                T.showShort(AdressActivity.this,jsonObject.getString("msg") + " 后台审核中...");
                                                finish();
                                            } else {
                                                T.showShort(AdressActivity.this,jsonObject.getString("msg"));
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                    }
                                });

                    } else {
                        T.showShort(this,"请完善地理位置");
                    }
                }


                break;
        }
    }
}
